package com.zhxh.nzpos.stock;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.zhxh.nzpos.BaseActivity;
import com.zhxh.nzpos.Constants;
import com.zhxh.nzpos.R;
import com.zhxh.nzpos.dao.GoodsDao;
import com.zhxh.nzpos.dao.StockDao;
import com.zhxh.nzpos.model.Goods;
import com.zhxh.nzpos.model.Stock;
import com.zhxh.nzpos.utils.ViewUtil;
import com.zhxh.nzpos.view.CustomDatePicker;

/**
 * 库存管理中的统计查询界面
 * 
 * @author wangzt
 *
 */
public class StockQueryInfoActivity extends BaseActivity {

	private static final int SEARCH_SUCCESS = 1;
	private static final int SEARCH_FAIL = 2;
	
	private ArrayList<Stock> stockItems;
	private StockQueryListAdapter listAdapter;
	
	private Calendar fromCal = Calendar.getInstance();
	private Calendar toCal = Calendar.getInstance();
	
	private EditText goodsCode;
	private Button searchBtn;
	
	private Button pageupBtn;
	private Button pagedownBtn;
	
	private StockDao stockDao;
	private GoodsDao goodsDao;
	private long total;
	private int pageSize = 6;
	private int currentPage = 1;
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == SEARCH_SUCCESS) {
				if (pageupBtn != null) {
					pageupBtn.setVisibility(View.GONE);
				}
				if (pagedownBtn != null) {
					pagedownBtn.setVisibility(View.GONE);
				}
				listAdapter.notifyDataSetChanged();
			}
			if (searchBtn != null) {
				searchBtn.setEnabled(true);
			}
			ViewUtil.cancelProgressDialog();
		}
		
	};
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stock_query);
        stockDao = new StockDao(getApplicationContext());
        goodsDao = new GoodsDao(getApplicationContext());
        initViews();
    }
	
	private void initViews() {
		stockItems = new ArrayList<Stock>();
		total = stockDao.getStockCount();
		if (pageSize > total) {
			stockItems.addAll(stockDao.getScrollData(currentPage, (int) total));
		} else {
			stockItems.addAll(stockDao.getScrollData(currentPage, pageSize));
		}
		
		ListView listView = (ListView) findViewById(R.id.stock_query_listview);
		
		listAdapter = new StockQueryListAdapter(getLayoutInflater(), stockItems);
		listView.setAdapter(listAdapter);
		
		pageupBtn = (Button) findViewById(R.id.stock_info_up_btn);
		pageupBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				int page = currentPage - 1;
				if (page > 0) {
					stockItems.clear();
					stockItems.addAll(stockDao.getScrollData(page, pageSize));
					currentPage = page;
					listAdapter.notifyDataSetChanged();
				}
			}
		});
		pagedownBtn = (Button) findViewById(R.id.stock_info_down_btn);
		pagedownBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				int page = currentPage + 1;
				if ((total - page * pageSize) > 0) {
					stockItems.clear();
					stockItems.addAll(stockDao.getScrollData(page, pageSize));
					currentPage = page;
					listAdapter.notifyDataSetChanged();
				}
			}
		});
		
		goodsCode = (EditText) findViewById(R.id.stock_goods_code_et);
		
		final EditText fromDate = (EditText)findViewById(R.id.stock_from_date);
		final EditText toDate = (EditText)findViewById(R.id.stock_to_date);
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		fromDate.setText(simpleDateFormat.format(fromCal.getTime()));
		toDate.setText(simpleDateFormat.format(toCal.getTime()));
        
		final CustomDatePicker fromPicker = new CustomDatePicker(this, fromDate, fromCal);
		fromDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				fromPicker.updateDate();
				fromPicker.show();
			}
		});
		
		final CustomDatePicker toPicker = new CustomDatePicker(this, fromDate, fromCal);
		toDate.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				toPicker.updateDate();
				toPicker.show();
			}
		});

		Button scanBtn = (Button) findViewById(R.id.stock_query_scan_btn);
		scanBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(Constants.SCAN_ACTION);
				startActivityForResult(intent, Constants.SCAN_REQUEST_CODE);
			}
		});
		
		searchBtn = (Button) findViewById(R.id.stock_search_btn);
		searchBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				searchBtn.setEnabled(false);
				ViewUtil.showProgressDialog(StockQueryInfoActivity.this, "正在查询...");
				new Thread() {
					public void run() {
						Editable goodE = goodsCode.getText();
						Editable fromE = fromDate.getText();
						Editable toE = toDate.getText();
						
						String code = "";
						if (goodE != null) {
							code = goodE.toString();
						}
						boolean handle = false;
						if ("".equals(code)) {
							ArrayList<Stock> stocks = stockDao.findByDate(fromE.toString(), toE.toString());
							if (stocks.size() > 0) {
								stockItems.clear();
								stockItems.addAll(stocks);
								handler.sendEmptyMessage(SEARCH_SUCCESS);
								handle = true;
							}
						} else {
							Goods goods = goodsDao.find(code);
							if (goods != null) {
								ArrayList<Stock> stocks = stockDao.findByGoodIdAndDate(goods.getId(), fromE.toString(), toE.toString());
								if (stocks.size() > 0) {
									stockItems.clear();
									stockItems.addAll(stocks);
									handler.sendEmptyMessage(SEARCH_SUCCESS);
									handle = true;
								}
							}
						}
						if (!handle) {
							handler.sendEmptyMessage(SEARCH_FAIL);
						}
					}
					
				}.start();
			}
		});
		Button backBtn = (Button) findViewById(R.id.stock_info_back_btn);
		backBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == Constants.SCAN_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				String ocrStr = intent.getStringExtra(Constants.SCAN_RESULT_EXTRA);
				if (!TextUtils.isEmpty(ocrStr)) {
					goodsCode.setText(ocrStr);
				} else {
					Toast.makeText(getApplicationContext(), "请重新扫描！",
							Toast.LENGTH_LONG).show();
				}

			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(getApplicationContext(), "请重新扫描！",
						Toast.LENGTH_LONG).show();
			}
		}
	}
}
